import PropertyDetails from './PropertyDetails'
import BaseTable from './BaseTable';
import Repository from '@/utils/repository'
import React, { createContext, useEffect, useState } from 'react';
import { TABLE_COLUMN } from './constants'
import type { PropertyContextType, customsetDataFun, PropertyContextValue } from './type'

export const PropertyContext = createContext<PropertyContextType | null>(null)

/**
 * 
 * @returns 
 */
const PropertyListings: React.FC = () => {
  const [data, setData] = useState<PropertyContextType>({ detailVisible: false, tableData: [], currentSelectProperty:{}, tableColumn: [] })
  const getDetail =async (id:number)=>{
    const repository = new Repository('property_detail')
    const data = await repository.getByIndex(id)
    return data
  }
  /**
   * 管理数据
   * @param key 数据键
   * @param value 数据值
   */
  const customsetData: customsetDataFun = async (key, value) => {
    let data:any = value
    //如果是改变currentSelectProperty的话直接拿仓库里的对应详情数据
    key==='currentSelectProperty'&&(data = await getDetail(value.id))

    setData((oldVal) => {
      return {
        ...oldVal,
        [key]: data
      }
    })
  }

  /**
   * 初始化数据
   */
  useEffect(() => {
    customsetData('tableColumn', TABLE_COLUMN)
    const repository = new Repository('property')
    repository.getList().then(data=>{
      const tableData = data.map((item) => ({
        ...item,
        addressText: item.address.city,
        propertyManagerText: item.propertyManager.name
      }))
      customsetData('tableData',tableData)
    })
  }, [])
  return (
    <PropertyContext.Provider value={{ ...data, customsetData } as PropertyContextValue}>
      <div>
        <BaseTable></BaseTable>
        < PropertyDetails />
      </div>
    </PropertyContext.Provider>
  );
};

export default PropertyListings;
